package com.tuoyu.peopletest.common;


import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Handler;
import android.text.TextUtils;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.Utils;
import com.tuoyu.peopletest.entity.message.ForegroundMessageEvent;
import com.tuoyu.peopletest.entity.message.NetWorkMessageEvent;
import com.tuoyu.peopletest.utils.MyThreadPoolUtils;
import com.tuoyu.peopletest.utils.SCFileUtils;
import com.tuoyu.peopletest.utils.SCLogUtils;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


/**
 * 自己重新定义application
 */
public class MyApplication extends Application {
    public static MyApplication myApp;

    private final static String TAG = "MyApplication";
    public static MyApplication mInstence;
    public static Context context;
    public static Handler mHandler;
    public int mainThreadId;
    //网络连接
    public static boolean isConnectNet;

    @Override
    public void onCreate() {
        super.onCreate();
        myApp=this;

        //三方工具类初始化
        Utils.init(this);
        isConnectNet = NetworkUtils.isConnected();
        //网络是否可用,
        //异步,有时用的时候, 不一定正确返回
        MyThreadPoolUtils.get().execute(() -> isConnectNet = NetworkUtils.isAvailable());

        mInstence = this;
        context = getApplicationContext();
        mHandler = new Handler();
        //获取主线程的线程id
        mainThreadId = android.os.Process.myTid();

        //数据库 初始化
        LitePal.initialize(this);

        setNetChangeListener();
        setAppStatusChangeListener();
        initBugly();
    }

    /**
     * bug收集
     */
    private void initBugly() {

        //开发的时候不使用
        if(Constant.isDevelop){
            return;
        }
        //腾讯的bugly,收集bug
//        Context context = getApplicationContext();
//        // 获取当前包名
//        String packageName = context.getPackageName();
//         // 获取当前进程名
//        String processName = getProcessName(android.os.Process.myPid());
//          // 设置是否为上报进程
//        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
//        strategy.setUploadProcess(processName == null || processName.equals(packageName));
//        CrashReport.initCrashReport(getApplicationContext(), "5d97b6aa63", false,strategy);
    }

    /**
     * 网络变化监听
     */
    private void setNetChangeListener() {
        NetworkUtils.registerNetworkStatusChangedListener(new NetworkUtils.OnNetworkStatusChangedListener() {
            @Override
            public void onDisconnected() {
                //发送通知
                EventBus.getDefault().post(new NetWorkMessageEvent().setNetChange( false, null));
            }

            @Override
            public void onConnected(NetworkUtils.NetworkType networkType) {
                //发送通知
                EventBus.getDefault().post(new NetWorkMessageEvent().setNetChange( true, networkType));
            }
        });
    }

    /**
     * app 前后台切换
     */
    private void setAppStatusChangeListener() {
        AppUtils.registerAppStatusChangedListener(new Utils.OnAppStatusChangedListener() {
            @Override
            public void onForeground(Activity activity) {
                SCLogUtils.e(TAG,"前台onForeground="+activity.toString());
                //SCLogUtils.e(TAG,"onForeground="+activity.getComponentName().getClassName());
                EventBus.getDefault().post(new ForegroundMessageEvent().setAppStatusChnage(true, activity));
            }

            @Override
            public void onBackground(Activity activity) {
                SCLogUtils.e(TAG,"退后台onBackground="+activity.toString());
                EventBus.getDefault().post(new ForegroundMessageEvent().setAppStatusChnage( false, activity));
            }
        });
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public Resources getResources() {//还原字体大小
        Resources res = super.getResources();
        Configuration configuration = res.getConfiguration();
        if (configuration.fontScale != 1.0f) {
            configuration.fontScale = 1.0f;
            res.updateConfiguration(configuration, res.getDisplayMetrics());
        }
        return res;
    }


}
